<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.customerName" placeholder="客户" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.deliveryOrderCode" placeholder="送货单号" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.directorBy" placeholder="负责人" />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
        </ASpace>
        <ASpace>
          <AButton type="primary" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        column-resizable
        size="small"
        :span-method="spanMethod"
      >
        <template #columns>
          <ATableColumn title="创建日期" data-index="createdDt" :width="100">
            <template #cell="{ record }">
              {{ dayjs(record.createdDt).format('YYYY-MM-DD') }}
            </template>
          </ATableColumn>
          <ATableColumn title="送货单号" data-index="deliveryOrderCode" :width="100">
          </ATableColumn>
          <ATableColumn title="所属客户" data-index="customerName" :width="100"> </ATableColumn>
          <ATableColumn title="产品" data-index="materialName" :width="100"> </ATableColumn>
          <ATableColumn title="规格型号" data-index="spec" :width="100"> </ATableColumn>
          <ATableColumn title="反馈问题" data-index="questionDesc" :width="100"> </ATableColumn>
          <ATableColumn title="处理意见" data-index="processSuggestion" :width="100">
          </ATableColumn>
          <ATableColumn title="数量" data-index="qty" :width="100"> </ATableColumn>
          <ATableColumn title="单位" data-index="unit" :width="100"> </ATableColumn>
          <ATableColumn title="单价" data-index="unitPrice" :width="100"> </ATableColumn>
          <ATableColumn title="金额" data-index="amt" :width="100">
            <template #cell="{ record }">
              {{ formatPrice(decimalRound(record.qty! * record.unitPrice!, 4)) }}
            </template>
          </ATableColumn>
          <ATableColumn title="处理结果" data-index="processResult" :width="100"> </ATableColumn>
          <ATableColumn title="负责人" data-index="directorBy" :width="100"> </ATableColumn>
          <ATableColumn title="含税" data-index="isInclTax" :width="70" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill v-if="record.isInclTax" style="color: #67c23a" size="20px" />
              <icon-close-circle-fill v-if="!record.isInclTax" style="color: red" size="20px" />
            </template>
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="100"> </ATableColumn>
          <ATableColumn v-if="isAuth([1, 2])" title="操作" :width="150" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="getTableData"
    ></EditPopupForm>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import deliveryBillPrint from './print.vue'
import dayjs from 'dayjs'
import { Message, Modal, TableInstance } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import { decimalRound, formatPrice } from '@renderer/utils/mixins'
import {
  delReturnReissue,
  getReturnReissueAllList,
  getReturnReissueDetail,
  getReturnReissuePageList,
  ReturnReissueListSearch,
  ReturnReissueResItem
} from '@renderer/api/logisticsDep'
import { isEmpty } from 'lodash-es'

const detailData = ref<ReturnReissueResItem>({
  returnReissueId: '',
  deliveryOrderId: '',
  deliveryOrderCode: '',
  customerId: '',
  customerName: '',
  isInclTax: 0,
  directorBy: '',
  remark: '',
  detailList: [],
  createdBy: '',
  createdDt: '',
  updatedBy: '',
  updatedDt: ''
}) // 打印数据
const searchFrom = ref<ReturnReissueListSearch>({})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<ReturnReissueResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const deliveryBillPrintRef = ref<InstanceType<typeof deliveryBillPrint>>() // 打印组件
const tableRef = ref<TableInstance>()

onMounted(() => {
  getTableData()
})

function formatData(baseData: ReturnReissueResItem[]) {
  return baseData
    .map((item) => {
      if (!isEmpty(item.detailList)) {
        return item.detailList.map((detailItem, index) => {
          if (index === 0) {
            return {
              ...detailItem,
              ...item,
              directorBy: detailItem.directorBy,
              span: item.detailList.length
            }
          } else {
            return { ...detailItem, ...item, directorBy: detailItem.directorBy }
          }
        })
      } else {
        return [item]
      }
    })
    .flat()
}
async function getTableData() {
  const res = await getReturnReissuePageList({ ...searchFrom.value, ...pageParam })
  tableData.value = formatData(res.data.list)
  pageParam.totalCount = res.data.totalCount!
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}
function onReset() {
  searchFrom.value = {}
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 3 || columnIndex > 12) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

function openEdit(title: string) {
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})
function rowEvent(row: ReturnReissueResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delReturnReissue({ returnReissueId: row.returnReissueId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    case 'print':
      getReturnReissueDetail({ returnReissueId: row.returnReissueId }).then((res) => {
        detailData.value = res.data
        nextTick(() => {
          deliveryBillPrintRef.value?.printInfo()
        })
      })
      break

    default:
      break
  }
}

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  const headerData = [
    { title: '创建日期', value: 'createdDt', width: 180 },
    { title: '送货单号', value: 'deliveryOrderCode' },
    { title: '所属客户', value: 'customerName' },
    { title: '产品', value: 'materialName' },
    { title: '规格型号', value: 'spec' },
    { title: '反馈问题', value: 'questionDesc' },
    { title: '处理意见', value: 'processSuggestion' },
    { title: '数量', value: 'qty' },
    { title: '单位', value: 'unit' },
    { title: '单价', value: 'unitPrice' },
    { title: '金额', value: 'amt' },
    { title: '处理结果', value: 'processResult' },
    { title: '负责人', value: 'directorBy' },
    { title: '含税', value: 'isInclTax' },
    { title: '备注', value: 'remark' }
  ]
  let excelData: ReturnReissueResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '退货补货数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getReturnReissueAllList(searchFrom.value)
        excelData = formatData(res.data.list).map((item, index) => {
          item.index = index + 1
          item.isInclTax = item.isInclTax ? '是' : '否'
          return item
        })
        console.log(excelData)
      }
      break
    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
